<template>
  <view class="realname-authentication">
    <!-- 顶部自定义导航 - 已修改为指定颜色 -->
    <tn-nav-bar fixed alpha customBack >
      <view slot="back" class='tn-custom-nav-bar__back' @click="goBack">
        <text class='icon tn-icon-left'></text>
      </view>
      <text class="nav-title"></text> <!-- 添加了导航栏标题 -->
    </tn-nav-bar>
	
	<!-- 顶部标题 -->
	<view class="page-header">
	  <view class="header-title">校友认证</view>
	</view>
	
    <view :style="{ paddingTop: vuex_custom_bar_height + 'px' }">
      <!-- 表单区域 -->
      <view class="form-container tn-padding-md tn-radius-lg form-container-top">
        <!-- 姓名 -->
        <view class="form-item">
          <text class="label">姓名</text>
          <tn-input 
            v-model="name" 
            placeholder="请输入姓名" 
            class="input-field" 
          />
        </view>

        <!-- 学号 -->
        <view class="form-item">
          <text class="label">学号</text>
          <tn-input 
            v-model="studentId" 
            placeholder="请输入学号" 
            class="input-field" 
          />
        </view>

        <!-- 学院 -->
        <view class="form-item">
          <text class="label">学院</text>
          <tn-input 
            v-model="college" 
            placeholder="请输入学院" 
            class="input-field" 
          />
        </view>

        <!-- 专业 -->
        <view class="form-item">
          <text class="label">专业</text>
          <tn-input 
            v-model="major" 
            placeholder="请输入专业" 
            class="input-field" 
          />
        </view>

        <!-- 证件号 -->
        <view class="form-item">
          <text class="label">证件号</text>
          <tn-input 
            v-model="idNumber" 
            placeholder="请输入18位身份证号" 
            class="input-field"
            :max-length="18"
            type="text"
          />
        </view>
      </view>

      <!-- 拍摄证件人像面 -->
      <view class="upload-container tn-margin-md tn-padding-md tn-radius-lg">
        <!-- 有图片时显示图片预览 -->
        <view v-if="cardFront && cardFront.length > 0" class="image-preview-container">
          <image 
            :src="cardFront[0]" 
            class="preview-image"
            mode="aspectFit"
            @click="openCamera"
          ></image>
          <view class="image-actions">
            <text class="replace-btn" @click="openCamera">重新选择</text>
          </view>
        </view>
        <!-- 没有图片时显示上传按钮 -->
        <view v-else>
          <view class="upload-btn" @click="openCamera">
            <image 
              src="/static/identity.png" 
              class="id-card-icon"
              mode="aspectFit"
            ></image>
            <text class="upload-text">拍摄证件人像面</text>
          </view>
          <view class="upload-tip tn-text-center tn-color-gray tn-padding-xs tn-text-sm">
            环境背景整洁、光线均匀<br>
            请确认已在手机设置应用开启摄像头权限
          </view>
        </view>
      </view>

      <!-- 提交按钮-->
      <view class="submit-btn-wrapper">
        <view class="custom-submit-btn" @click="submit">
          <text class="submit-btn-text">提交</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import TnNavBar from '@/tuniao-ui/components/tn-nav-bar/tn-nav-bar.vue'
import TnInput from '@/tuniao-ui/components/tn-input/tn-input.vue'
import TnButton from '@/tuniao-ui/components/tn-button/tn-button.vue'
import { submitAlumniCard } from '@/appApi/user.js'

export default {
  components: {
    TnNavBar,
    TnInput,
    TnButton
  },
  data() {
    return {
      name: '',
      studentId: '',
      college: '',
      major: '',
      idNumber: '',
      cardFront: [] // 可后续扩展上传逻辑
    }
  },
  methods: {
	goBack() {
	    uni.navigateBack({
	        delta: 1
	    });
	    }, 
    openCamera() {
      uni.chooseImage({
        count: 1,
        sourceType: ['camera', 'album'], // 允许拍照或从相册选择
        success: (res) => {
          const tempFilePaths = res.tempFilePaths
          this.cardFront = tempFilePaths
          console.log('上传路径:', tempFilePaths)
        },
        fail: (err) => {
          console.error('选择图片失败:', err)
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          })
        }
      })
    },
    // 处理证件类型选择变化
    handleIdTypeChange(e) {
      const index = e.detail.value
      this.idTypeIndex = index
      this.idType = this.idTypeOptions[index]
    },
    submit() {
      // 表单验证
      if (!this.name || !this.name.trim()) {
        uni.showToast({
          title: '请输入姓名',
          icon: 'none'
        })
        return
      }
      if (!this.studentId || !this.studentId.trim()) {
        uni.showToast({
          title: '请输入学号',
          icon: 'none'
        })
        return
      }
      if (!this.college || !this.college.trim()) {
        uni.showToast({
          title: '请输入学院',
          icon: 'none'
        })
        return
      }
      if (!this.major || !this.major.trim()) {
        uni.showToast({
          title: '请输入专业',
          icon: 'none'
        })
        return
      }
      if (!this.idNumber || !this.idNumber.trim()) {
        uni.showToast({
          title: '请输入证件号',
          icon: 'none'
        })
        return
      }
      // 验证身份证号长度（必须是18位）
      const trimmedIdNumber = this.idNumber.trim()
      if (trimmedIdNumber.length !== 18) {
        uni.showToast({
          title: '身份证号必须是18位',
          icon: 'none'
        })
        return
      }
      if (!this.cardFront || this.cardFront.length === 0) {
        uni.showToast({
          title: '请拍摄证件人像面',
          icon: 'none'
        })
        return
      }

      // 显示加载提示
      uni.showLoading({
        title: '提交中...',
        mask: true
      })

      // 先上传图片，获取图片URL
      const uploadImage = (filePath) => {
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: 'http://localhost:8080/common/upload',
            filePath,
            name: 'file',
            // ① 关键修复：把 token 带过去
            header: {
              Authorization: uni.getStorageSync('token') || ''
            },
            success: (uploadRes) => {
              try {
                const result = JSON.parse(uploadRes.data)
                if (result.code === 200) {
                  resolve(result.url || result.data)
                } else {
                  reject(new Error(result.msg || '图片上传失败'))
                }
              } catch (e) {
                reject(new Error('图片上传响应解析失败'))
              }
            },
            fail: reject
          })
        })
      }

      // 上传图片并提交表单
      const submitData = async () => {
        try {
          let idImage1 = ''
          // 如果有图片，先上传获取URL
          if (this.cardFront && this.cardFront.length > 0) {
            idImage1 = await uploadImage(this.cardFront[0])
          }

          // 构建请求数据
          const requestData = {
            realName: this.name.trim(),
            studentId: this.studentId.trim(),
            college: this.college.trim(),
            major: this.major.trim(),
            idNumber: this.idNumber.trim(),
            idImage1: idImage1
          }

          // 发送请求到后端接口
          submitAlumniCard(requestData)
            .then((res) => {
              uni.hideLoading()
              if (res.code === 200) {
                uni.showToast({
                  title: '提交成功',
                  icon: 'success',
                  duration: 2000
                })
                // 延迟返回上一页
                setTimeout(() => {
                  uni.navigateBack({
                    delta: 1
                  })
                }, 1500)
              } else {
                // 检查是否是学号重复的错误
                const errorMsg = res.msg || '提交失败'
                const errorMsgLower = errorMsg.toLowerCase()
                // 检查多种可能的错误提示：学号重复、已存在、exist等
                if ((errorMsg.includes('学号') || errorMsg.includes('studentId') || errorMsg.includes('student_id')) && 
                    (errorMsg.includes('重复') || errorMsg.includes('已存在') || errorMsg.includes('exist') || 
                     errorMsgLower.includes('duplicate') || errorMsgLower.includes('already'))) {
                  uni.showToast({
                    title: '学号已存在',
                    icon: 'none',
                    duration: 3000
                  })
                } else {
                  uni.showToast({
                    title: errorMsg,
                    icon: 'none',
                    duration: 2000
                  })
                }
              }
            })
            .catch((error) => {
              uni.hideLoading()
              console.error('请求失败:', error)
              uni.showToast({
                title: error.response?.data?.msg || error.message || '网络请求失败',
                icon: 'none'
              })
            })
        } catch (error) {
          uni.hideLoading()
          console.error('提交失败:', error)
          uni.showToast({
            title: error.message || '提交失败',
            icon: 'none'
          })
        }
      }

      submitData()
    }
  }
}
</script>

<style lang="scss" scoped>
/* 自定义导航栏返回按钮样式 */
.tn-custom-nav-bar__back {
	width: 60%;
	height: 100%;
	position: relative;
	display: flex;
	justify-content: space-evenly;
	align-items: center;
	box-sizing: border-box;
	background-color: rgba(0, 0, 0, 0.15);
	border-radius: 1000rpx;
	border: 1rpx solid rgba(255, 255, 255, 0.5);
	color: #FFFFFF;
	font-size: 18px;

	.icon {
		display: block;
		flex: 1;
		margin: auto;
		text-align: center;
	}
}	
	
.realname-authentication {
  background-color: #f5f5f5; /* 与donate.vue页面背景色一致 */
  min-height: 100vh;
}

 .nav-title {
  color: #FFFFFF;
  font-size: 36rpx;
  font-weight: bold;
  margin: 0 20rpx;
}

/* 顶部标题样式 */
.page-header {
  padding: 20rpx 20rpx;
  text-align: center;
  color: black;
  margin-top: 80rpx;
  margin-bottom: 20rpx; /* 调整下边距，适配小程序 */
  
  .header-title {
    font-size: 48rpx;
    font-weight: bold;
    margin-bottom: 0;
    letter-spacing: 2rpx;
  }
}

/* 小程序环境下的间距调整 - 缩小50% */
/* #ifdef MP-WEIXIN */
.page-header {
  margin-bottom: 5rpx;
}
/* #endif */

// 表单容器
.form-container {
  background: #ffffff; /* 白色背景 */
  border-radius: 16rpx; /* 更大圆角 */
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05); /* 更明显阴影 */
  border: none; /* 移除边框 */
  
  &.form-container-top {
    margin: 0rpx 30rpx 24rpx 30rpx; /* 左右下边距，上边距由 page-header 的 margin-bottom 控制 */
  }
}

// 上传容器
.upload-container {
  background: #ffffff; /* 白色背景 */
  border-radius: 16rpx; /* 更大圆角 */
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05); /* 更明显阴影 */
  border: none; /* 移除边框 */
}

// 统一间距样式
.tn-margin-md {
  margin: 24rpx 30rpx;
}
.tn-padding-md {
  padding: 20rpx;
}
.tn-radius-lg {
  border-radius: 16rpx;
}

.form-item {
  display: flex;
  flex-direction: column;
  padding: 18rpx 0;
  position: relative;

  // 表单项分隔线
  &:not(:last-child)::after {
    content: '';
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 1rpx;
    background-color: #f0f0f0;
  }

  .label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 14rpx;
    font-weight: 500;
  }

  // 输入框样式
  .input-field {
    width: 100%;
    border: 2rpx solid #e5e5e5; /* 边框粗细和颜色与donate.vue一致 */
    border-radius: 12rpx;
    padding: 20rpx 24rpx;
    font-size: 28rpx;
    color: #333;
    background-color: white;
    transition: all 0.2s ease;
    box-sizing: border-box; /* 确保宽度计算包含内边距和边框 */

    &:focus {
      border-color: #1F4D4B; /* 聚焦色与主题色一致 */
      box-shadow: 0 0 0 3rpx rgba(31, 77, 75, 0.2); /* 主题色的浅色光晕 */
      outline: none;
    }

    &::placeholder {
      color: #c0c0c0;
      font-weight: 400;
    }
  }

 

  .picker-display {
    width: 100%;
    text-align: left;
    color: #333;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
  }

  .picker-arrow {
    color: #999;
    font-size: 32rpx;
  }
}

.id-card-icon {
  height: 70rpx;
  margin-bottom: 10rpx;
  font-size: 70rpx;
}

.upload-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 220rpx;
  border: 2rpx dashed #1F4D4B; /* 边框与主题色呼应 */
  border-radius: 12rpx;
  background-color: rgba(31, 77, 75, 0.05); /* 主题色的浅色背景 */
  cursor: pointer;
  transition: all 0.2s ease;

  &:active {
    background-color: rgba(31, 77, 75, 0.1); /* 激活时背景色更深 */
  }
  .upload-text {
    font-size: 26rpx;
    color: #1F4D4B; /* 上传文字与主题色呼应 */
    font-weight: 500;
  }
}

.upload-tip {
  margin-top: 10rpx;
  line-height: 1.5;
}

/* 图片预览容器样式 */
.image-preview-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.preview-image {
  width: 600rpx;
  height: 400rpx;
  border-radius: 12rpx;
  border: 2rpx solid #e5e5e5;
  background-color: #f5f5f5;
  object-fit: contain; /* 保持图片比例，完整显示 */
}

.image-actions {
  margin-top: 20rpx;
  width: 100%;
  display: flex;
  justify-content: center;
}

.replace-btn {
  padding: 12rpx 40rpx;
  background-color: #1F4D4B;
  color: white;
  border-radius: 8rpx;
  font-size: 26rpx;
  font-weight: 500;
}

.submit-btn-wrapper {
  padding: 30rpx 40rpx;
}

/* 提交按钮样式 - 深青色胶囊形状，兼容浏览器和微信小程序 */
.custom-submit-btn {
  width: 100%;
  background-color: #1F4D4B;
  border-radius: 50rpx;
  box-shadow: 0 8rpx 24rpx rgba(31, 77, 75, 0.3);
  padding: 24rpx 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  transition: all 0.3s ease;
}

.custom-submit-btn:active {
  opacity: 0.9;
  transform: scale(0.98);
  box-shadow: 0 4rpx 12rpx rgba(31, 77, 75, 0.2);
}

.submit-btn-text {
  color: #ffffff;
  font-weight: bold;
  font-size: 32rpx;
  line-height: 1;
}
</style>